package com.jiong.ad.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiong.ad.entity.AdCategory;
import com.jiong.ad.entity.Advertisement;
import com.jiong.ad.mapper.AdvertisementMapper;
import com.jiong.ad.service.IAdCategoryService;
import com.jiong.ad.service.IAdvertisementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiong.ad.vo.AdVO;
import com.jiong.common.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 广告表 服务实现类
 * </p>
 *
 * @author jiong
 * @since 2025-01-16
 */
@Service
public class AdvertisementServiceImpl extends ServiceImpl<AdvertisementMapper, Advertisement> implements IAdvertisementService {

    @Autowired
    IAdCategoryService adCategoryService;

    @Override
    public PageResult<Advertisement> findByPage(Integer page, Integer pageSize) {
        Page<Advertisement> AdPage = this.page(new Page<>(page, pageSize));
        AdPage.getRecords().forEach(ad -> {
            AdCategory adCategory = adCategoryService.getById(ad.getCategoryId());
            if (adCategory != null) {
                ad.setCategoryName(adCategory.getName());
            }
        });
        return new PageResult<>(AdPage.getRecords(), AdPage.getTotal());
    }

    @Override
    public PageResult<Advertisement> search(Integer page, Integer pageSize, AdVO adVO) {
        // 构建查询条件
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(adVO.getTitle()), "title", adVO.getTitle())
                .like(StrUtil.isNotBlank(adVO.getUrl()), "url", adVO.getUrl())
                .eq(adVO.getCategoryId() != null, "category_id", adVO.getCategoryId());

        // 执行分页查询
        Page<Advertisement> songsPage = this.page(new Page<>(page, pageSize), queryWrapper);

        // 遍历查询结果，设置广告种类名称
        songsPage.getRecords().forEach(advertisement -> {
            AdCategory adCategory = adCategoryService.getById(advertisement.getCategoryId());
            if (adCategory != null) {
                advertisement.setCategoryName(adCategory.getName());
            }
        });
        return new PageResult<>(songsPage.getRecords(), songsPage.getTotal());
    }

    @Override
    public boolean add(Advertisement advertisement) {
        return this.save(advertisement);
    }
}
